#include "pointparser.h"
#include <QStringList>
#include <QDebug>

QList<QPointF> PointParser::parse(const QString &text) const
{
    if (text.isEmpty()) return {};

    // 尝试逗号分隔
    QList<QPointF> points = parseCommaSeparated(text);
    if (!points.isEmpty()) return points;

    // 尝试空格分隔
    points = parseSpaceSeparated(text);
    return points;
}

//按逗号解析文本
QList<QPointF> PointParser::parseCommaSeparated(const QString &text) const
{
    QList<QPointF> points;
    QStringList parts = text.split(QRegExp("[,\\s]+"), Qt::SkipEmptyParts);
    
    if (parts.size() % 2 != 0) return {};

    for (int i = 0; i < parts.size(); i += 2) {
        bool ok1, ok2;
        qreal x = parts[i].toDouble(&ok1);
        qreal y = parts[i + 1].toDouble(&ok2);
        
        if (!ok1 || !ok2) return {};
        
        points.append(QPointF(x, y));
    }
    
    return points;
}

//按空格解析文本
QList<QPointF> PointParser::parseSpaceSeparated(const QString &text) const
{
    QList<QPointF> points;
    QStringList parts = text.split(QRegExp("\\s+"), Qt::SkipEmptyParts);
    
    if (parts.size() % 2 != 0) return {};

    for (int i = 0; i < parts.size(); i += 2) {
        bool ok1, ok2;
        qreal x = parts[i].toDouble(&ok1);
        qreal y = parts[i + 1].toDouble(&ok2);
        
        if (!ok1 || !ok2) return {};
        
        points.append(QPointF(x, y));
    }
    
    return points;
}

bool PointParser::isNumber(const QString &str) const
{
    bool ok;
    str.toDouble(&ok);
    return ok;
}


QList<QPointF> PointParser::parseCoordinates(const QString& s) {
    QList<QPointF> result;
    
    // 按行分割字符串（以分号作为行分隔符）
    QStringList lines = s.split(';', Qt::SkipEmptyParts);
    
    for (const QString& line : lines) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.isEmpty()) {
            continue;
        }
        
        // 按逗号分割坐标
        QStringList coords = trimmedLine.split(',', Qt::SkipEmptyParts);
        if (coords.size() != 2) {
            // 如果不是两个值，跳过这一行
            continue;
        }
        
        bool okX, okY;
        qreal x = coords[0].trimmed().toDouble(&okX);
        qreal y = coords[1].trimmed().toDouble(&okY);
        
        if (okX && okY) {
            result.append(QPointF(x, y));
        }
    }
    
    return result;
}